package com.ben.chatroom.session;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.AttributeKey;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author huangyijun
 */
@Slf4j
public class ClientSession {

  public static final AttributeKey<ClientSession> SESSION_KEY = AttributeKey.valueOf("SESSION_KEY");
  public static final AttributeKey<Boolean> IS_LOGIN = AttributeKey.valueOf("IS_LOGIN");

  @Setter
  @Getter
  private Channel channel;

  @Setter
  @Getter
  private String sessionId;

  @Setter
  @Getter
  private boolean isConnected = false;

  public ClientSession(Channel channel) {
    this.channel = channel;
    this.sessionId = String.valueOf(-1);
    channel.attr(SESSION_KEY).set(this);
  }

  /**
   * 断开连接
   */
  public void close() {
    this.isConnected = false;
    ChannelFuture future = channel.close();
    future.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if(future.isSuccess()) {
          log.error("顺利断开连接!!!");
          channel.attr(IS_LOGIN).set(false);
        }
      }
    });
  }
}
